package com.caipin.utils;

/**
 * @Author: zhunian0322@163.com
 * @DateTime: 2021-10-06 12:33
 * @Description: TODO
 */

@Component
public class CheveretoUtils {
    private static final Logger log = LoggerFactory.getLogger(com.caipin.utils.CheveretoUtils.class);

    private int TIMEOUT = 3000;

    @Value("${chevereto.key}")
    private String key;

    @Value("${chevereto.host}")
    private String host;

    @Value("${chevereto.port}")
    private Integer port;

    @Value("${chevereto.url}")
    private String pathUrl;

    public String sendImageBase64ToChevereto(String imageBase64) {
        CloseableHttpResponse closeableHttpResponse;
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(this.TIMEOUT).setConnectionRequestTimeout(this.TIMEOUT).setSocketTimeout(this.TIMEOUT).setRedirectsEnabled(true).build();
        StringBuilder url = new StringBuilder();
        url.append("http://").append(this.host).append(":").append(this.port).append(this.pathUrl);
        HttpPost httpPost = new HttpPost(url.toString());
        httpPost.setConfig(requestConfig);
        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();
        entityBuilder.addTextBody("key", this.key, ContentType.MULTIPART_FORM_DATA)
                .addTextBody("source", imageBase64, ContentType.MULTIPART_FORM_DATA);
        HttpEntity httpEntity = entityBuilder.build();
        httpPost.setEntity(httpEntity);
        HttpResponse resp = null;
        try {
            closeableHttpResponse = httpClient.execute((HttpUriRequest)httpPost);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (closeableHttpResponse != null) {
            HttpEntity respEntity = closeableHttpResponse.getEntity();
            if (closeableHttpResponse.getStatusLine().getStatusCode() == 200) {
                try {
                    String result = EntityUtils.toString(respEntity);
                    log.info(result);
                    return result;
                } catch (IOException e) {
                    e.printStackTrace();
                }
            } else {
                String s = null;
                try {
                    s = EntityUtils.toString(respEntity);
                    log.error(s);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                log.info(s);
            }
            return null;
        }
        return null;
    }
}

